#!/usr/bin/env python2
import pygal
import time
import os
import datetime
import sqlite3
import sys


BASEDIR = os.path.split(os.path.realpath(__file__))[0]

DBFILE = BASEDIR + os.sep + "MonitorMQ.db"

def dataRange():
    chlist = ['One Hour','One Day','Half Day']
    count = 0
    ch = 0
    beginTime = ''
    endTime  =  ''
    name =  ''
    tablename = ''
    for item in chlist:
        print '%d. %s' %(count,item)
        count = count + 1
    while True:
        ch = raw_input('select one:')
        try:
            ch = int(ch)
        except Exception as e:
            ch = ch
            print "error choice!"
            continue
        if ch ==0:
            beginTime =  (datetime.datetime.now() - datetime.timedelta(hours=1) ).strftime("%Y-%m-%d %H:%M:%S")
            endTime =  time.strftime('%Y-%m-%d %H:%M:%S')
            tablename = "MQmonitor_" + '_'.join(beginTime.split('-')[:2])
            break
        if ch == 1:
            beginTime =  (datetime.datetime.now() - datetime.timedelta(days=1) ).strftime("%Y-%m-%d %H:%M:%S")
            endTime =  time.strftime('%Y-%m-%d %H:%M:%S')
            tablename = "MQmonitor_" + '_'.join(beginTime.split('-')[:2])
            break
        if ch == 2:
            beginTime =  (datetime.datetime.now() - datetime.timedelta(hours=12) ).strftime("%Y-%m-%d %H:%M:%S")
            endTime =  time.strftime('%Y-%m-%d %H:%M:%S')
            tablename = "MQmonitor_" + '_'.join(beginTime.split('-')[:2])
            break
        else:
            print "error choice !"
    SQL = "select distinct(name) from %s" %tablename
    namelist = []
    try:
        connection = sqlite3.connect(DBFILE)
        cursor = connection.cursor()
        data = cursor.execute(SQL).fetchall()
        connection.close()
    except :
        print "cannot find data in the monitor table "
        sys.exit(1)
    for i in data:
        namelist.append(i[0])

    count = 0
    for item in namelist :
        print '%d . %s' %(count,item)
        count = count + 1
    while True :
        ch = raw_input('select one:')
        try:
            ch = int(ch)
        except Exception as e:
            ch = ch
            print "error choice!"
            continue
        if ch < len(namelist) and ch >= 0 :
            name = namelist[ch]
            break
    return tablename,name,beginTime,endTime




def getMonthMnotirData(tablename,name,beginTime, endTime ):
    SQL = '''select name,pending,consumers,enqueued,dequeued,MonitorTime
	from %s
	where MonitorTime >= "%s"
	and MonitorTime <= "%s"
	and name = "%s"'''  % (tablename,beginTime,endTime,name)
    connection = sqlite3.connect(DBFILE)
    cursor = connection.cursor()
    data = cursor.execute(SQL).fetchall()
    connection.close()
    return data



def createGal(data):
    name = ''
    try:
        name = data[0][0]
    except Exception as e:
        pass
    pending = []
    consumers = []
    enqueued = []
    dequeued = []
    MonitorTime = []
    for item in data:
        pending.append( item[1])
        consumers.append( item[2])
        enqueued.append( item[3])
        dequeued.append( item[4])
        MonitorTime.append( item[5])
    line_chart = pygal.Line()
    line_chart.title = 'ActiveMQ  - %s - pending'%name
    line_chart.x_labels = MonitorTime
    line_chart.add('pending', pending)
    line_chart.render()
    line_chart1 = pygal.Line()
    line_chart1.title = 'ActiveMQ  - %s - consumers'%name
    line_chart1.x_labels = MonitorTime
    line_chart1.add('consumers', consumers)
    line_chart1.render()
    line_chart2 = pygal.Line()
    line_chart2.title = 'ActiveMQ  - %s - enqueued'%name
    line_chart2.x_labels = MonitorTime
    line_chart2.add('enqueued', enqueued)
    line_chart2.render()
    line_chart3 = pygal.Line()
    line_chart3.title = 'ActiveMQ  - %s - dequeued'%name
    line_chart3.x_labels = MonitorTime
    line_chart3.add('dequeued', dequeued)
    line_chart3.render()
    return line_chart,line_chart1,line_chart2,line_chart3


def oneDayReport():
    beginTime =  (datetime.datetime.now() - datetime.timedelta(days=1) ).strftime("%Y-%m-%d %H:%M:%S")
    endTime =  time.strftime('%Y-%m-%d %H:%M:%S')
    tablename = "MQmonitor_" + '_'.join(beginTime.split('-')[:2])
    namelist = ["alarmInfo.hbase.mysql","attackAlarmAnalysis.hbase","attackDireAnalysis.hbase","attackWorkupAnalysis.hbase","monitorListener1","monitorListener2","monitorListener3","monitorResultQueue","performance.hbase.mysql","performanceAlarm.hbase.mysql","saveSafedogConfigFile.hbase","scanQueue","serverBaseInfo.mysql","serverInfrequentInfo.hbase.mysql","serverInstalledAppInfo.mysql","serverProcess.hbase.mysql","serverRemotLogin.hbase","serverResourceInfo.hbase","serverServiceInfo.mysql","serverWebsiteInfo.mysql","unsafeInfo.mysql"]
    #tablename,name,beginTime,endTime  = dataRange()
    saveDir = BASEDIR + os.sep + 'html'+ os.sep + time.strftime("%Y%m%d")
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)
    for name in namelist:
        data = getMonthMnotirData(tablename,name,beginTime, endTime )
        line_charts = createGal(data)
        line  = ''
        filename = (name+'_'+beginTime +' - '+ endTime + '.html').replace(' ','_').replace(':','')
        contents = '''<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>%s</title>

</head>
<body>
    ''' %name
        f=open(saveDir+ os.sep+filename,'a')
        f.write(contents)
        for line_chart in line_charts:
            f.write(line_chart.render())
        contents = """
</body>
</html>
     """
        f.write(contents)
        f.close()
        print saveDir+ os.sep+filename

def main():
    tablename,name,beginTime,endTime  = dataRange()
    data = getMonthMnotirData(tablename,name,beginTime, endTime )
    saveDir = BASEDIR + os.sep + 'html'+ os.sep + 'tmp'
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)
    line_charts = createGal(data)
    line  = ''
    filename = (name+'_'+beginTime +' - '+ endTime + '.html').replace(' ','_').replace(':','')
    contents = '''<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>%s</title>

</head>
<body>
    ''' %name
    f=open(saveDir+os.sep+filename,'a')
    f.write(contents)
    for line_chart in line_charts:
        f.write(line_chart.render())
    contents = """
</body>
</html>
     """
    f.write(contents)
    f.close()
    print saveDir+ os.sep+filename
    return saveDir + os.sep+filename

if __name__ == "__main__":
    argvs  = sys.argv
    if len(argvs) > 1:
        if argvs[1] == 'oneday':
            oneDayReport()
    else:
        main()
